<template>
  <div>
    <el-card style="margin:20px 0">
      <CategorySelect :show="!defTable" @select="select" />
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <!-- 默认状态 -->
      <div v-show="defTable">
        <!-- 添加的按钮 -->
        <el-button
          v-show="$store.state.user.buttons.indexOf('btn.Attr.add')!==-1"
          type="primary"
          icon="el-icon-plus"
          style="margin:10px 0"
          :disabled="category3Id===''"
          @click="addAttr"
        >添加属性</el-button>

        <!-- 表格 -->
        <el-table
          :data="list"
          style="width: 100%"
          border
        >
          <template slot="empty">
            <el-empty description="空" />
          </template>
          <el-table-column
            prop="prop"
            label="序号"
            width="80px"
            type="index"
            align="center"
          />
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150px"
          />
          <el-table-column
            prop="prop"
            label="属性值列表"
            width="width"
          >
            <template slot-scope="{row}">
              <div>
                <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin:0 10px" type="success">
                  {{ item.valueName }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="200px"
          >
            <template slot-scope="{row}">
              <el-button type="warning" icon="el-icon-edit" size="mini" :disabled="$store.state.user.buttons.indexOf('btn.Attr.update')===-1" @click="edit(row)">修改</el-button>
              <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="$store.state.user.buttons.indexOf('btn.Attr.remove')===-1" @click="del(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 添加|修改 -->
      <div v-show="!defTable">
        <el-form ref="form" :inline="true">
          <el-form-item label="属性名">
            <el-input v-model="attrInfo.attrName" placeholder="请输入属性名" />
          </el-form-item>
        </el-form>
        <el-button type="primary" icon="el-icon-plus" :disabled="attrInfo.attrName===''" @click="addValue">添加属性值</el-button>
        <el-button>取消</el-button>

        <el-table
          style="width: 100%;margin-top:22px;margin-bottom:10px"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column
            prop="prop"
            label="序号"
            align="center"
            width="80px"
            type="index"
          />
          <template slot="empty">
            <el-empty description="空" />
          </template>
          <el-table-column
            prop="prop"
            label="属性值名称"
            width="width"
          >
            <template slot-scope="{row,$index}">
              <el-input v-if="row.flag===true" :ref="$index" v-model.trim="row.valueName" placeholder="请输入属性值名称" @blur="blue(row)" />
              <div v-else @click="toEdit(row,$index)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column
            prop="prop"
            label="操作"
            width="150px"
          >
            <template slot-scope="{row,$index}">
              <div>
                <el-popconfirm
                  :title="`确定删除${row.valueName}吗?`"
                  @confirm="delValue(row,$index)"
                >
                  <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini" />
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" :disabled="attrInfo.attrName===''" @click="saveAttrInfo">保存</el-button>
        <el-button @click="defTable=true">取消</el-button>
      </div>
    </el-card>

  </div>
</template>

<script>
// 引入lodash中的深拷贝
import { cloneDeep } from 'lodash'
export default {
  name: 'Attr',
  data() {
    return {
      category1Id: '',
      category2Id: '',
      category3Id: '',
      list: [],
      defTable: true,
      // 收集新增属性|修改属性
      attrInfo: {
        attrName: '', // 属性名
        attrValueList: [], // 属性值
        categoryId: 0, // 三级分类id
        categoryLevel: 3 // 区分是几级id
      }
    }
  },
  methods: {
    select({ categoryId, level }) {
      if (level === 1) {
        this.category1Id = categoryId
        this.category2Id = ''
        this.category3Id = ''
      } else if (level === 2) {
        this.category2Id = categoryId
        this.category3Id = ''
      } else if (level === 3) {
        this.category3Id = categoryId
        this.getData()
      }
    },
    async getData() {
      const data = { category1Id: this.category1Id, category2Id: this.category2Id, category3Id: this.category3Id }
      const res = await this.$api.attr.attrInfoList(data)
      if (res.code === 200) {
        this.list = res.data
      }
    },
    async del(e) {
      try {
        await this.$api.attr.deleteAttr(e.id)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('删除失败')
      }
      this.getData()
    },
    delValue(e, index) {
      e.valueName = ''
      this.attrInfo.attrValueList.splice(index, 1)
    //   this.saveAttrInfo()
    },
    // 添加属性值
    addValue() {
      // attrId是服务器返回的，目前手里没有所以就直接作为undefined
      // 为每个元素添加一个flag用于切换输入与显示模式
      // 只有用户点击添加的时候才会具有flag字段,服务器返回的并没有flag字段,所以可以默认将服务器返回的值的状态设置为span模式
      this.attrInfo.attrValueList.push({ attrId: this.attrInfo.id || undefined, valueName: '', flag: true })
      this.$nextTick(() => {
        // 添加后也自动聚焦
        this.$refs[this.attrInfo.attrValueList.length - 1].focus()
      })
    },
    // 跳转到添加的页面
    addAttr() {
      // 清除数据
      this.defTable = false
      this.attrInfo.attrName = ''
      this.attrInfo.attrValueList = []
      this.attrInfo.categoryId = this.category3Id
    },
    // 跳转到修改页面
    edit(e) {
      this.defTable = false
      // 包含数组的对象的拷贝需要用到深拷贝(数据结构复杂)
      this.attrInfo = cloneDeep(e)
      // 服务器返回的数据没有flag字段,所以需要循环加入
      this.attrInfo.attrValueList.forEach(item => {
        // 不能使用非响应式的方法(因为是对象的变化,所以VUE没办法检测到)
        // item.flag = false
        // 响应式的方法(vue没办法检测到对象的变化,所以需要用$set修改)
        this.$set(item, 'flag', false)
      })
    },
    // 失去焦点时候的操作
    blue(e) {
      if (e.valueName === '') {
        this.$message.error('不能为空')
        return
      }
      // some方法检测数组中的元素是否含有满足指定的值(出现重复的值就返回true)
      const isRepat = this.attrInfo.attrValueList.some(item => {
        if (e !== item) {
          // 出现重复的话就返回重复项
          return e.valueName === item.valueName
        }
      })
      if (isRepat) {
        this.$message.error('不能出现重复项')
        e.valueName = ''
        return
      }
      e.flag = false
    },
    // 点击的操作
    toEdit(row, index) {
      row.flag = true
      // 在dom节点加载完毕的时候再去获取
      this.$nextTick(() => {
        // 调用foucs方法自动聚焦,并且让当前元素切换到编辑状态
        this.$refs[index].focus()
      })
    },
    // 保存添加或者修改的属性
    async saveAttrInfo() {
      // 重新收集过滤完成后的数据
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(item => {
        if (item.valueName !== '') {
          // 删除掉flag属性
          delete item.flag
          // 返回true,代表着过滤完成返回了新数组
          return true
        }
      })
      try {
        await this.$api.attr.saveAttrInfo(this.attrInfo)
        this.defTable = true
        this.getData()
        this.$message({
          message: '保存成功',
          type: 'success'
        })
      } catch (error) {
        this.$message.error('保存失败')
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
